package com.jlwl.houseservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jlwl.houseservice.common.JwtTokenUtil;
import com.jlwl.houseservice.entity.Administrator;
import com.jlwl.houseservice.mapper.AdministratorMapper;
import com.jlwl.houseservice.service.AdministratorService;
import com.jlwl.houseservice.vo.AdminLoginVO;
import com.jlwl.houseservice.vo.LoginResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 管理员Service实现类
 */
@Service
public class AdministratorServiceImpl extends ServiceImpl<AdministratorMapper, Administrator> implements AdministratorService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public LoginResultVO login(AdminLoginVO adminLoginVO) {
        // 进行身份验证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        adminLoginVO.getUsername(),
                        adminLoginVO.getPassword()
                )
        );

        // 设置认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 生成JWT令牌
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtTokenUtil.generateToken(userDetails);

        // 更新管理员最后登录时间
        Administrator admin = getOne(new LambdaQueryWrapper<Administrator>()
                .eq(Administrator::getUsername, adminLoginVO.getUsername()));
        admin.setLastLoginTime(LocalDateTime.now());
        updateById(admin);

        // 构建返回结果
        LoginResultVO loginResultVO = new LoginResultVO();
        loginResultVO.setId(admin.getId());
        loginResultVO.setUsername(admin.getUsername());
        loginResultVO.setRealName(admin.getRealName());
        loginResultVO.setAvatar(admin.getAvatar());
        loginResultVO.setRole(admin.getRole());
        loginResultVO.setToken(token);
        loginResultVO.setLastLoginTime(admin.getLastLoginTime());

        return loginResultVO;
    }
} 